<template>
  <div class="carbon-emission-container">
    <el-row :gutter="20">
      <!-- 左侧环形图 -->
      <el-col :span="14">
        <div class="chart-container">
          <div id="pieChart" style="width: 100%; height: 400px;"></div>
        </div>
      </el-col>

      <!-- 右侧数据表格 -->
      <el-col :span="10">
        <div class="data-container">
          <!-- 总体指标表格 -->
          <el-table :data="overallData" style="width: 100%; margin-bottom: 20px;" border>
            <el-table-column prop="item" label="总体指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>

          <!-- 强度指标表格 -->
          <el-table :data="intensityData" style="width: 100%;" border>
            <el-table-column prop="item" label="强度指标" width="180"></el-table-column>
            <el-table-column prop="value" label="数值"></el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listAll } from '@/api/business/engineering'

export default {
  name: 'CarbonEmission',
  data() {
    return {
      // 环形图实例
      pieChart: null,
      // 总体指标数据
      overallData: [
        { item: '工程总体碳排放', value: '3998.13 KgCO₂e' },
        { item: '勘察设计', value: '120' },
        { item: '建材生产运输', value: '240' },
        { item: '施工阶段', value: '300' },
        { item: '运营维护', value: '342' },
        { item: '拆除处置', value: '390' },
      ],
      // 强度指标数据
      intensityData: [
        { item: '单位里程碳排放强度', value: '35.05 kgCO₂e/Km' },
        { item: '年均碳排放强度', value: '35.05 kgCO₂e/a' }
      ],
      // 环形图配置
      chartOption: {
        title: {
          text: '工程碳排放占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['勘察设计', '建材生产运输', '施工阶段', '运营维护', '拆除处置']
        },
        series: [
          {
            name: '工程碳排放',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: `{a|3998.13 KgCO₂e}\n{b|35.05 kgCO₂e/(m²·a)}`,
              rich: {
                a: {
                  fontSize: 16,
                  fontWeight: 'bold',
                  color: '#333',
                  lineHeight: 26
                },
                b: {
                  fontSize: 14,
                  color: '#666',
                  lineHeight: 20
                }
              }
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 10, name: '勘察设计', itemStyle: { color: '#ffc53d' } },
              { value: 3.99, name: '建材生产运输', itemStyle: { color: '#73d13d' } },
              { value: 3.21, name: '施工阶段', itemStyle: { color: '#409eff' } },
              { value: 10.00, name: '运营维护', itemStyle: { color: '#2c9d93' } },
              { value: 5.21, name: '拆除处置', itemStyle: { color: '#3e3a3a' } },
            ]
          }
        ]
      }
    }
  },
  mounted() {
    const engineeringId = this.$route.params && this.$route.params.engineeringId
    const projectId = this.$route.params && this.$route.params.projectId
    const mileage = this.$route.query && this.$route.query.mileage
    const serviceLife = this.$route.query && this.$route.query.serviceLife
    listAll({projectId: projectId, engineeringId: engineeringId}).then((res) => {
      let result = 0
      // 创建新的数据数组，保持原有结构
      const newChartData = []

      for (let i = 1; i < this.overallData.length; i++) {
        let currentResult
        currentResult = res.data[i - 1].totalEmission ? res.data[i - 1].totalEmission.toFixed(2) : 0
        this.overallData[i].value = `${currentResult.toString()}`

        // 保持原有数据结构，只更新value值
        newChartData.push({
          value: parseFloat(currentResult),
          name: this.chartOption.series[0].data[i - 1].name,
          itemStyle: this.chartOption.series[0].data[i - 1].itemStyle
        })

        result = result + parseFloat(currentResult)
      }

      // 更新总体数据和强度指标
      this.overallData[0].value = `${result.toFixed(2)} KgCO₂e`
      this.intensityData[0].value = `${(result/parseFloat(mileage)).toFixed(2)} KgCO₂e/Km`
      this.intensityData[1].value = `${(result/parseFloat(serviceLife)).toFixed(2)} KgCO₂e/a`

      // 更新图表数据
      this.chartOption.series[0].data = newChartData

      // 更新中心标签
      this.chartOption.series[0].label.formatter = `{a|${result.toFixed(2)} KgCO₂e}\n{b|${(result/parseFloat(mileage)).toFixed(2)} kgCO₂e/Km}`

      this.initChart()
      // 响应窗口大小变化
      window.addEventListener('resize', this.handleResize)
    })
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.pieChart) {
      this.pieChart.dispose();
      this.pieChart = null;
    }
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    // 初始化图表
    initChart() {
      const chartDom = document.getElementById('pieChart');
      this.pieChart = echarts.init(chartDom);
      this.pieChart.setOption(this.chartOption);
    },
    // 处理窗口大小变化
    handleResize() {
      if (this.pieChart) {
        this.pieChart.resize();
      }
    }
  }
}
</script>

<style scoped>
.carbon-emission-container {
  padding: 20px;
  background-color: #fff;
}

.chart-container, .data-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
}

/* 调整表格样式 */
.el-table {
  font-size: 14px;
}

.el-table::before {
  height: 0;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .el-col {
    width: 100%;
  }
}
</style>
